<template>
  <div class="login" v-if="flag">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <div style="display: flex;margin: 0px auto 30px auto;justify-content: center;">
        <img v-bind:src="logoImage" alt="" style="width: 69px; height: 69px; margin: 5px 10px 5px 5px">
        <h3 class="title">{{ system.YQDA_SYSTEM_NAME }}<span style="color: red">{{ system.YQDA_MJ_LEVEL }}</span></h3>
      </div>
      <el-form-item prop="userType">
        <el-select @change="userTypeOnchangeMethod" v-show="isShowSoloTenant" v-model="loginForm.userType"
          style="width: 100%" placeholder="请选择用户类型">
          <el-option v-for="item in userTypeOptions" :key="item.userTypeCode" :label="item.userTypeName"
            :value="item.userTypeCode"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="isShowTenant" prop="tenantCode">
        <el-select v-model="loginForm.tenantCode" style="width: 100%" placeholder="请选择立档单位">
          <el-option v-for="item in tenantOptions" :key="item.tenantCode" :label="item.registeredUnit"
            :value="item.tenantCode"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码"
          @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
          @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" plain size="mini" style="float: right;cursor: pointer;" @click="handleUkey"
          v-show="isShowUkey">ukey登录</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :loading="loading" size="medium" type="primary" style="width:100%;"
          @click.native.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>{{ system.YQDA_SYSTEM_COPYRIGHT }}</span>
    </div>
  </div>
  <div v-else>
    <div v-loading.fullscreen.lock="true"></div>
  </div>
</template>
<script>
import { getCodeImg, getSoloTenant, getSingleSignOn, singleSignOn, systemName } from "@/api/login";
import { listOption } from "@/api/manage/manageUser";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getToken, setToken, setExpiresIn, removeToken } from '@/utils/auth'
import { ssologin } from "@/api/homePage";
import { getFlag } from "@/api/UkeyLogin";
import { iszt } from '@/api/archive/dict/dictManageData'
export default {
  name: "Login",
  data() {
    return {
      system: "",
      userTypeOptions: [
        { userTypeCode: "tenant", userTypeName: "立档单位" },
        { userTypeCode: "manager", userTypeName: "管理单位" }
      ],
      tenantOptions: [],
      isShowTenant: false,
      isShowSoloTenant: true,
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
        userType: "",
        tenantCode: undefined
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        userType: [
          { required: true, trigger: "change", message: "请选择用户类型" }
        ],
        /*tenantId: [
          { required: true, trigger: "change", message: "请选择立档单位" }
        ],*/
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      soloTenant: undefined,
      flag: false,
      code: undefined,
      state: undefined,
      isShowUkey: false,
      logoImage: "",
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getTenantOptions();
    // 根据后端返回值判断ukey登录按钮是否展示
    getFlag().then(res => {
      this.isShowUkey = res.data
    })

    const search = window.location.search;
    const cleanQueryString = search.slice(1);
    // 将查询字符串拆分成键值对
    const keyValuePairs = cleanQueryString.split('&');
    // 创建一个空对象来存储键值对
    const params = {};
    // 将键值对存储到对象中
    keyValuePairs.forEach(pair => {
      const [key, value] = pair.split('=');
      params[key] = decodeURIComponent(value);
    });
    const id = params.id
    if (id != undefined && id != null && id != '') {
      this.flag = false
      ssologin({ id: id }).then(response => {
        sessionStorage.setItem("needInit", response.data.needInit)
        setToken(response.data.access_token)
        // commit('SET_TOKEN', data.access_token)
        setExpiresIn(response.data.expires_in)
        // commit('SET_EXPIRES_IN', data.expires_in)
        // resolve()
        if (sessionStorage.getItem("needInit") == "false") {
          //this.$router.push({ path: "/index" || "/" }).catch(()=>{});
          if (sessionStorage.getItem("isUpdatePwd") == 'true') {
            this.$router.replace({ path: "/updatePwd" })
          } else {
            iszt().then(response => {//判断是否是中铁项目1 是  其余返回的数据都不是中铁项目
              sessionStorage.setItem("IS_ZT", response);
            })
            this.$router.push({ path: this.redirect || "/" }).catch(() => { });
          }
        } else {
          this.$router.push({ path: "/initialization" })
        }
      })
    }

    this.getCode();
    this.getCookie();
    this.soloTenant = this.$route.query.soloTenant;
    this.isSoloTenant(this.soloTenant);
    this.getSingleSignOnCode();



    //登陆标题
    systemName().then(res => {
      this.system = res.data;
      this.logoImage = require('@/assets/logo/' + res.data.YQDA_SYSTRM_LOG)
    })
  },
  methods: {
    userTypeOnchangeMethod() {
      var that = this;
      that.loginForm.username = '';
      that.loginForm.password = '';
      that.loginForm.rememberMe = false;
      that.loginForm.code = '';
      //that.loginForm.uuid = '';
      that.loginForm.tenantCode = undefined;
      if (this.loginForm.userType == 'tenant') {
        this.isShowTenant = true;
        this.loginRules['tenantCode'] = [{ required: true, trigger: 'change', message: '请选择立档单位' }];
      } else {
        this.loginRules['tenantCode'] = '';
        this.isShowTenant = false;
      }

    },
    getSingleSignOnCode() {
      if (this.$route.query.sanyuan == "true") {
        this.flag = true;
        return;
      }
      getSingleSignOn().then(resp => {
        //内蒙古政府办单点
        if (resp.data.ssoType == 'nmgzfb') {
          if (resp.data.singleSignOn) {
            this.flag = false;
            localStorage.setItem("singleSignOn", resp.data.singleSignOn);
            //localStorage.setItem("clientId",resp.data.clientId);
            localStorage.setItem("OAuthPath", resp.data.OAuthPath);
            localStorage.setItem("ssoType", 'nmgzfb');
            localStorage.setItem("appId", resp.data.appId);
            localStorage.setItem("redirectPath", resp.data.redirectPath);
            this.code = this.$route.query.code;
            //this.state = this.$route.query.state;
            if (this.code != undefined) {
              //跳转回来的地址，执行单点登录逻辑
              singleSignOn(this.code).then(resp => {
                this.$message.success("登录成功");
                sessionStorage.setItem("needInit", resp.data.needInit)
                localStorage.setItem("uid", resp.data.uid);
                setToken(resp.data.access_token)
                setExpiresIn(resp.data.expires_in)
                if (sessionStorage.getItem("needInit") == "false") {
                  //this.$router.push({ path: "/index" || "/" }).catch(()=>{});
                  if (sessionStorage.getItem("isUpdatePwd") == 'true') {
                    this.$router.replace({ path: "/updatePwd" })
                  } else {
                    iszt().then(response => {//判断是否是中铁项目1 是  其余返回的数据都不是中铁项目
                      sessionStorage.setItem("IS_ZT", response);
                    })
                    this.$router.push({ path: this.redirect || "/" }).catch(() => { });
                  }
                } else {
                  this.$router.push({ path: "/initialization" })
                }
              })
            } else {
              var u = resp.data.OAuthPath + "/open/authorize?redirect_uri=" + resp.data.redirectPath + "&" +
                "app_id=" + resp.data.appId + "&response_type=code";
              // console.log("跳转地址申请code=========="+u);
              //还未申请临时code，跳转地址申请临时code
              window.location.href = u;
            }

          } else {
            this.flag = true;
          }
        } else {

          if (resp.data.singleSignOn) {
            this.flag = false;
            localStorage.setItem("singleSignOn", resp.data.singleSignOn);
            localStorage.setItem("clientId", resp.data.clientId);
            localStorage.setItem("OAuthPath", resp.data.OAuthPath);
            localStorage.setItem("redirectPath", resp.data.redirectPath);
            this.code = this.$route.query.code;
            this.state = this.$route.query.state;
            if (this.code != undefined && this.state != undefined) {
              //跳转回来的地址，执行单点登录逻辑
              singleSignOn(this.code).then(resp => {
                this.$message.success("登录成功");
                sessionStorage.setItem("needInit", resp.data.needInit)
                setToken(resp.data.access_token)
                setExpiresIn(resp.data.expires_in)
                if (sessionStorage.getItem("needInit") == "false") {
                  //this.$router.push({ path: "/index" || "/" }).catch(()=>{});
                  if (sessionStorage.getItem("isUpdatePwd") == 'true') {
                    this.$router.replace({ path: "/updatePwd" })
                  } else {
                    iszt().then(response => {//判断是否是中铁项目1 是  其余返回的数据都不是中铁项目
                      sessionStorage.setItem("IS_ZT", response);
                    })
                    this.$router.push({ path: this.redirect || "/" }).catch(() => { });
                  }
                } else {
                  this.$router.push({ path: "/initialization" })
                }
              })
            } else {

              //还未申请临时code，跳转地址申请临时code
              window.location.href = resp.data.OAuthPath + "/idp/oauth2/authorize?redirect_uri=" + resp.data.redirectPath + "?redirect=" + this.redirect +
                "&state=243909&client_id=" + resp.data.clientId + "&response_type=code";
            }

          } else {
            this.flag = true;
          }
        }
      })
    },
    isSoloTenant(soloTenant) {
      getSoloTenant().then(resp => {
        if (soloTenant == 'true') {
          this.isShowSoloTenant = false;
          this.loginForm.userType = "tenant";
          this.loginForm.tenantCode = resp.data.soloTenantCode;
          this.loginRules.userType = [];
        } else if (resp.data.isSoloTenant == true) {
          this.isShowSoloTenant = false;
          this.loginForm.userType = "tenant";
          this.loginForm.tenantCode = resp.data.soloTenantCode;
          this.loginRules.userType = [];
        }
      });
    },
    getTenantOptions() {
      listOption().then(response => {
        this.tenantOptions = response.tenantOptions;
      });
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm.username = username === undefined ? this.loginForm.username : username
      this.loginForm.password = password === undefined ? this.loginForm.password : decrypt(password),
        this.loginForm.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe)

    },
    handleLogin() {
      console.log(this.loginForm, "skldfjklsdjfklsdjfklsdj")
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          sessionStorage.clear()
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }


          this.$store.dispatch("Login", this.loginForm).then((responseData) => {
            // 这里会接收到 resolve() 方法传递的数据
            // 如果 API 返回了 200 状态码，并且你在 action 中调用了 resolve(response.data)
            console.log('Login successful:', responseData)
            //sessionStorage.getItem("logindata")  true=="初始化页面"  false==“主页面”
            //  console.log(sessionStorage.getItem("needInit"),"======================")
            localStorage.setItem("soloTenant", this.soloTenant);
            localStorage.setItem("VUE_APP_BASE_API", process.env.VUE_APP_BASE_API);
            if (sessionStorage.getItem("needInit") == "false") {
              if (responseData.data.INIT_SYSTEM == "true") {
                this.$router.replace({ path: "/initialization1" })
              } else {
                if (sessionStorage.getItem("isUpdatePwd") == 'true') {
                  this.$router.replace({ path: "/updatePwd" })
                } else {
                  iszt().then(response => {//判断是否是中铁项目1 是  其余返回的数据都不是中铁项目
                    sessionStorage.setItem("IS_ZT", response);
                  })
                  this.$router.push({ path: this.redirect || "/" }).catch(() => { });
                }
              }
            } else {
              this.$router.replace({ path: "/initialization" })
            }
          }).catch((error) => {
            // 这里会接收到 reject() 方法传递的错误
            console.log('Login failed:', error);
            if (error == 402) { //跳转登陆页授权功页面
              this.$router.push({ path: "/authorizationFunction" })
            } else {
              this.loading = false;
              if (this.captchaEnabled) {
                this.getCode();
              }
            }

          });
        }
      });
    },
    // ukey登录 跳转页面
    handleUkey() {
      console.log("sdlkfjsdkljf")
      this.$router.push({
        path: "/UkeyLogin",
        query: {
          redirect: this.redirect
        },
      })
      // this.$refs.loginForm.validate(valid => {
      //   if (valid) {
      //     sessionStorage.clear()
      //     this.loading = true;
      //     if (this.loginForm.rememberMe) {
      //       Cookies.set("username", this.loginForm.username, { expires: 30 });
      //       Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
      //       Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
      //     } else {
      //       Cookies.remove("username");
      //       Cookies.remove("password");
      //       Cookies.remove('rememberMe');
      //     }
      //     this.$store.dispatch("Login", this.loginForm).then(() => {
      //       //sessionStorage.getItem("logindata")  true=="初始化页面"  false==“主页面”
      //       console.log(sessionStorage.getItem("needInit"),"======================")
      //       localStorage.setItem("soloTenant",this.soloTenant);
      //       this.$router.replace({path:"/UkeyLogin"})
      //     }).catch(() => {
      //       this.loading = false;
      //       if (this.captchaEnabled) {
      //         this.getCode();
      //       }
      //     });
      //   }
      // });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: 100% 100%;
}

.login-form .el-form-item {
  width: 400px !important;
  margin: 0 auto 20px auto;
}

.title {
  // margin: 0px auto 30px auto;
  margin: 0;
  padding: 0;
  line-height: 80px;
  text-align: center;
  // color: #707070;
  color: #3f6cd6;
  font-weight: bold;
  font-size: 34px;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;

  padding: 25px 25px 5px 25px;
  position: absolute;
  right: 13%;
  //top: 29%;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}
</style>
